package org.luckyjourney.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.luckyjourney.entity.File;
import org.luckyjourney.entity.agent.*;
import org.luckyjourney.entity.agent.vo.AudioText;
import org.luckyjourney.entity.user.User;
import org.luckyjourney.entity.vo.AgentPageVo;
import org.luckyjourney.entity.vo.AgentSessionVo;
import org.luckyjourney.entity.vo.AgentTokenVo;
import org.luckyjourney.holder.UserHolder;
import org.luckyjourney.service.FileService;
import org.luckyjourney.service.agent.*;
import org.luckyjourney.service.user.UserService;
import org.luckyjourney.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.luckyjourney.entity.vo.AgentVo;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.test.AIQuestionAnswering;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author 飒飒
 * @ClassName agentController
 * @description: TODO
 * @date 2024年03月13日
 * @version: 1.0
 */
@RestController
@RequestMapping("/luckyjourney/agent")
@Api(tags = "智能体")
@Slf4j
public class agentController {

    @Autowired
    private AgentTableService agentTableService;

    @Autowired
    private AgentCategoryService agentCategoryService;

    @Autowired
    private AgentChatService agentChatService;

    @Autowired
    private AgentToneService agentToneService;

    @Autowired
    private UserService userService;

    @Autowired
    private AgentChatTableService agentChatTableService;

    //咨询师资料
    @Autowired
    private CouselorService couselorService;

    @Autowired
    private FileService fileService;

    @Value("${file.path}")
    private String filePath;


    private static final String BASE_URL = "http://82.157.234.84:8091/";
//    private static final String BASE_URL = "http://192.168.1.233:5000/";


    private static  String appKey="ybVRMrtEqGFmRCtm";
    private static String ALIYUN_AK_ID="LTAIZkuwP3heevhN";
    private static String ALIYUN_AK_SECRET="D8p1QkmsgDyk5r91ym4K5lbScBus1p";

    /**
     * 类型查询
     * @param
     * @return
     */
    @GetMapping("/findList")
    @ApiOperation("类型查询")
    public R findList() {
        List<AgentCategory> list = agentCategoryService.list(null);
        return R.ok().data(list);
    }

    /**
     * 智能体查询所有
     * @return
     */
    @PostMapping("/toneAll/{agentId}")
    @ApiOperation("查询所有音色")
    public R toneAll(@PathVariable int agentId,@RequestBody AgentPageVo agentPageVo) {
        Page<AgentTone> agentTonePage = new Page<>(agentPageVo.getPage(),agentPageVo.getSize());
        AgentTable agentTable = agentTableService.getById(agentId);

        if (1==agentTable.getUsageToneId() && !StringUtils.isEmpty(agentTable.getUsageToneId())){
            //如果音色id不为null
           AgentTone agentTone=agentToneService.getById(agentTable.getUsageToneId());
           if (!StringUtils.isEmpty(agentTone.getUserId())){
               //如果有用户id
               return R.ok().data(agentTone);
           }
        }
        //内地音色
        IPage<AgentTone> list = agentToneService.page(agentTonePage, null);
        return R.ok().data(list);
    }


    @PostMapping("/updatAgentTone/{toneId}/{agent_chat_id}")
    @ApiOperation("修改智能体对话的音色")
    public R updatAgentTone(@PathVariable Integer toneId,@PathVariable int agent_chat_id) {
        if (StringUtils.isEmpty(toneId)){
            return R.error().message("音色id不能为空");
        }
        if(StringUtils.isEmpty(agent_chat_id)){
            return R.error().message("智能体对话id不能为空");
        }
        AgentChatTable chatTable = agentChatTableService.getById(agent_chat_id);
        chatTable.setUsageToneId(toneId);
        agentChatTableService.saveOrUpdate(chatTable);
        return R.ok();

    }


    /**
     * 根据分类id查询智能体
     * @param
     * @return
     */
    @PostMapping("/findList/{agent_category_id}")
    @ApiOperation("根据分类id查询智能体")
    public R findList(
                      @PathVariable int agent_category_id,
                      @RequestParam(required = false) Integer userId,
                      @RequestBody AgentPageVo agentPageVo
    ) {
        if (StringUtils.isEmpty(agent_category_id)){
            return R.error().message("分类id不能为空");
        }
//        agentTableService.findList()
        //根据分类id查询智能体
        LambdaQueryWrapper<AgentTable> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AgentTable::getAgentCategoryId,agent_category_id);
        Page<AgentTable> page = new Page<>(agentPageVo.getPage(),agentPageVo.getSize());
        IPage<AgentTable> list = agentTableService.page(page, wrapper);
        List<AgentTable> agentList = list.getRecords();
        //将头像照片赋值进去
        agentList.forEach(agent -> {
            if(!StringUtils.isEmpty(agent.getAgentProfile())){
                Long avatar = Long.valueOf(agent.getAgentProfile());
                File fileTrustUrl = fileService.getFileTrustUrl(avatar);
                if (!ObjectUtils.isEmpty(fileTrustUrl)){
                    agent.setAgentProfile(fileTrustUrl.getFileKey());
                }
            }
            agent.setInChat(false);
        });
        //判断是否是已添加到对话列表
//        Long userId = UserHolder.get();
        if (!StringUtils.isEmpty(userId) || !agentList.isEmpty()){
            List<AgentChatTable> tableList = agentChatTableService.list(new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getUserId,userId ));
            tableList.forEach(table -> {
                //过滤调table.agentId和agentList集合中agentId不相同的数据,
                // 并且将Inchat赋值为true

                List<AgentTable> collect = agentList.stream().filter(agent -> agent.getAgentId().equals(table.getAgentId())).collect(Collectors.toList());
                collect.stream().forEach(agent -> {
                    agent.setInChat(true);
                    agent.setAgentChatId(table.getAgentChatId());
                });
                /*agentList.forEach(agent -> {
                    if (agent.getAgentId().equals(table.getAgentId())){
                        agent.setInChat(true);
                        agent.setAgentChatId(table.getAgentChatId());
                    }
                });*/
            });
        }

        //用户将智能体添加到对话的数量
        agentList.forEach(agent -> {
            agent.setChatsCount(agentChatTableService.count(new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getAgentId, agent.getAgentId())));
        });
        if (StringUtils.isEmpty(UserHolder.get())){
            agentList.forEach(agent -> {
                agent.setInChat(false);
            });
        }
        return R.ok().data(list);
    }

    /**
     * 模糊查询智能体
     * @param agentName
     * @return
     */
    @PostMapping("/findByName/{agentName}")
    @ApiOperation("模糊查询智能体")
    public R findByName(@PathVariable String agentName,@RequestBody AgentPageVo agentPageVo){
        IPage<AgentTable> agentTables=agentTableService.getByName(agentName,agentPageVo);
        return R.ok().data(agentTables);
    }

    /**
     * 智能体查询
     * @param
     * @return
     */
    @GetMapping("/findById/{id}")
    @ApiOperation("根据智能体id查询")
    public R findById(@PathVariable int id) {
        AgentTable agentTable = agentTableService.getById(id);
        //将头像照片赋值进去
        if(!StringUtils.isEmpty(agentTable.getAgentProfile())){
            Long avatar = Long.valueOf(agentTable.getAgentProfile());
            File fileTrustUrl = fileService.getFileTrustUrl(avatar);
            if (!ObjectUtils.isEmpty(fileTrustUrl)){
                agentTable.setAgentProfile(fileTrustUrl.getFileKey());
            }
        }
        agentTable.setChatsCount(agentChatTableService.count(new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getAgentId, agentTable.getAgentId())));
        if (!StringUtils.isEmpty(agentTable.getUsageToneId())){
            AgentTone byId = agentToneService.getById(agentTable.getUsageToneId());
            agentTable.setToneName(byId.getToneName());
        }
        return R.ok().data(agentTable);
    }

    /**
     * 新增智能体对话
     * @param agent_id
     * @return
     */
    @PostMapping("/newAgentChat/{agent_id}")
    @ApiOperation("新增智能体对话")
    public R newAgentChat(@PathVariable Integer agent_id) {
        //根据智能体查询智能体信息
        AgentTable agentTable = agentTableService.getById(agent_id);
        AgentChatTable agentChatTable = new AgentChatTable();
        BeanUtils.copyProperties(agentTable, agentChatTable);
        Integer userId= Math.toIntExact(UserHolder.get());
        agentChatTable.setUserId(userId);
        agentChatTable.setCreateTime(new Date());
        AgentChatTable chatTable = agentChatTableService.getOne(new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getAgentId, agentTable.getAgentId()).eq(AgentChatTable::getUserId, userId));
        if (ObjectUtils.isEmpty(chatTable)){
            //新增
            boolean save = agentChatTableService.save(agentChatTable);
            AgentChatTable chatTable1 = agentChatTableService.getOne(new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getAgentId, agentTable.getAgentId()).eq(AgentChatTable::getUserId, userId));
            return R.ok().data(save?chatTable1.getAgentChatId():"新增失败");
        }else {
            //已经存在
            return R.ok().data("已经存在");
        }
    }

    @PostMapping("/findAgentChatList")
    @ApiOperation("智能体对话列表")
    public R findAgentChatList(@RequestBody AgentPageVo agentPageVo) {
        Integer userId= Math.toIntExact(UserHolder.get());
        if (ObjectUtils.isEmpty(userId)){
            return R.error().message("用户未登录");
        }
        Page<AgentChatTable> page = new Page<>(agentPageVo.getPage(),agentPageVo.getSize());
        LambdaQueryWrapper<AgentChatTable> wrapper = new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getUserId, userId);
        //根据isTop排序,为true在前 false在后
        wrapper.orderByDesc(AgentChatTable::getIsTop);
        IPage<AgentChatTable> iPage = agentChatTableService.page(page, wrapper);
        List<AgentChatTable> list = iPage.getRecords();
        //将头像照片赋值进去
        list.forEach(comment -> {
            if(!StringUtils.isEmpty(comment.getAgentProfile())){
                Long avatar = Long.valueOf(comment.getAgentProfile());
                File fileTrustUrl = fileService.getFileTrustUrl(avatar);
                if (!ObjectUtils.isEmpty(fileTrustUrl)){
                    comment.setAgentProfile(fileTrustUrl.getFileKey());
                }
            }
        });
        list.forEach(agentChatTable -> {
            List<AgentChat> list1 = agentChatService.list(new LambdaQueryWrapper<AgentChat>().eq(AgentChat::getAgentChatId, agentChatTable.getAgentChatId()).eq(AgentChat::getUserId, UserHolder.get()).orderByDesc(AgentChat::getCreateTime));
            if (!ObjectUtils.isEmpty(list1)){
                agentChatTable.setAgentPrologueAndChat(list1.get(0).getAgentMsg());
            }
        });
        list.forEach(agentChatTable -> {
            agentChatTable.setChatsCount(agentChatService.count(new LambdaQueryWrapper<AgentChat>().eq(AgentChat::getAgentChatId, agentChatTable.getAgentChatId())));
        });
        return R.ok().data(iPage);
    }

    /**
     * 根据智能体对话id查询
     * @param agent_chat_id
     * @return
     */
    @GetMapping("/findAgentChat/{agent_chat_id}")
    @ApiOperation("根据智能体对话id查询")
    public R findAgentChat(@PathVariable Integer agent_chat_id) {
        if (StringUtils.isEmpty(agent_chat_id)){
            return R.error().message("智能体对话id不能为空");
        }
       AgentChatTable agentChatTable = agentChatTableService.getAgentChatByid(agent_chat_id);
        //不为空
        if (!StringUtils.isEmpty(agentChatTable.getUsageToneId())){
            AgentTone byId = agentToneService.getById(agentChatTable.getUsageToneId());
            agentChatTable.setToneName(byId.getToneName());
        }
//        agent
       return R.ok().data(agentChatTable);
    }



    /**
     * 删除智能体对话
     * @param agent_chat_id
     * @return
     */
    @DeleteMapping("/removeAgentChat/{agent_chat_id}")
    @ApiOperation("删除智能体对话")
    public R removeAgentChat(@PathVariable Integer agent_chat_id) {
        if (StringUtils.isEmpty(agent_chat_id)){
            return R.error().message("智能体对话id不能为空");
        }
        return R.ok().data(agentChatTableService.removeById(agent_chat_id));
    }

    /**
     * 置顶或取消置顶
     * @param agent_chat_id
     * @return
     */
    @PostMapping("/isTopAndUpTop/{agent_chat_id}")
    @ApiOperation("置顶或取消置顶")
    public R isTopAndUpTop(@PathVariable Integer agent_chat_id) {
        if (StringUtils.isEmpty(agent_chat_id)){
            return R.error().message("智能体对话id不能为空");
        }
        String isTopAndUpTop =agentChatTableService.isTopAndUpTop(agent_chat_id);
        return R.ok().data(isTopAndUpTop);
    }


    /**
     * ai对话
     * @param agentSessionVo
     * @return
     */
    @PostMapping("newChatAndAGnetChat")
    @ApiOperation("未添加智能体对的ai问答对话")
    public R newChatAndAGnetChat(@RequestBody AgentSessionVo agentSessionVo) throws Exception {
        //根据智能体查询智能体信息
        AgentTable agentTable = agentTableService.getById(agentSessionVo.getAgent_id());
        //智能体对话
        AgentChatTable agentChatTable = new AgentChatTable();
        BeanUtils.copyProperties(agentTable, agentChatTable);
        int userId= Math.toIntExact(UserHolder.get());
        agentChatTable.setCreateTime(new Date());
        agentChatTable.setUserId(userId);
        agentChatTableService.save(agentChatTable);
        //查询到新增的智能体对话的id
        AgentChatTable chatTable = agentChatTableService.getOne(new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getAgentId, agentSessionVo.getAgent_id()).eq(AgentChatTable::getUserId, userId));
        String token = generateSecureToken();
        String s = HttpUtil.HttpsGetJson(BASE_URL+"chat/new_chat", token, "agent_chat_id="+chatTable.getAgentChatId()+"&user_msg="+URLEncoder.encode(agentSessionVo.getUser_chat(), "UTF-8")+"&user_id="+userId, "POST");
//        String substring = s.substring(28);
        //json类型转Map类型
//        Map mapObj = JSONObject.parseObject(substring,Map.class);
        return R.ok().data(s);
    }




    /**
     * ai对话
     * @param agentSessionVo
     * @return
     */
    @PostMapping(value = "newChat", produces = MediaType.TEXT_PLAIN_VALUE)
    @ApiOperation("已添加智能体对的ai问答对话")
    public R newChat(@RequestBody AgentSessionVo agentSessionVo) throws Exception {
        int userId= Math.toIntExact(UserHolder.get());
        //查询到新增的智能体对话的id
        AgentChatTable chatTable = agentChatTableService.getOne(new LambdaQueryWrapper<AgentChatTable>().eq(AgentChatTable::getAgentChatId, agentSessionVo.getAgent_id()).eq(AgentChatTable::getUserId, userId));
        String token = generateSecureToken();
//        String s = HttpUtil.HttpsGetJson(BASE_URL+"chat/new_chat",  token, "agent_chat_id="+chatTable.getAgentChatId()+"&user_msg="+URLEncoder.encode(agentSessionVo.getUser_chat(), "UTF-8")+"&user_id="+userId+"&model_name="+URLEncoder.encode("ERNIE-Bot","UTF-8"), "POST");
        String s = HttpUtil.doPost(BASE_URL + "chat/new_chat?agent_chat_id=" + chatTable.getAgentChatId() + "&user_msg=" + URLEncoder.encode(agentSessionVo.getUser_chat(), "UTF-8") + "&user_id=" + userId + "&model_name=" + URLEncoder.encode("ERNIE-Bot", "UTF-8"), null);
//        AIQuestionAnswering.main();
//        String substring = s.substring(28);
        //json类型转Map类型
//        Map mapObj = JSONObject.parseObject(substring,Map.class);
        return R.ok().data(s);
    }

    @PostMapping("/listCouselor")
    @ApiOperation("咨询师随机推荐")
    public R listCouselor() {
        //随机推荐5位咨询师
        List<Couselor> list = couselorService.list(new LambdaQueryWrapper<Couselor>().last("limit 5"));
        // 创建Random对象生成随机数
        Random random = new Random();
        List<Couselor> couselors = new ArrayList<>();
        // 生成7个不重复随机数
        while (couselors.size() < 5) {
            // 生成1到32之间的随机数
            int num = random.nextInt(list.size());
            //下标为num的对象
            Couselor couselor = list.get(num);
            // 将随机数添加到Set集合中
            couselors.add(couselor);
        }
        return R.ok().data(couselors);
    }

    /**
     * 删除聊天记录
     * @param
     * @return
     */
    @DeleteMapping("/removeByIdAll/{agent_chat_id}")
    @ApiOperation("删除聊天记录")
    public R removeById(@PathVariable int agent_chat_id) {
        if (StringUtils.isEmpty(agent_chat_id)){
            return R.error().message("智能体对话id不能为空");
        }
      int agentChat= agentChatService.bathRemoveById(agent_chat_id);
        if (agentChat==0){
            return R.error().message("删除失败");
        }
       /* // 构造安全的token
        String token = generateSecureToken();
        Long userId = UserHolder.get();
        HttpUtil.HttpsGetJson(BASE_URL + "chat/remove_by_id", token, "user_id=" +userId +"&chat_id="+chat_id, "POST");*/
        return R.ok().message("删除成功");
    }

    /**
     *
     * @param chat_id
     * @return
     */
    @DeleteMapping("/removeByIdChat/{chat_id}")
    @ApiOperation("删除ai问答对话")
    public R removeByIdChat(@PathVariable int chat_id) {
        if (StringUtils.isEmpty(chat_id)){
            return R.error().message("ai对话id不能为空");
        }
        boolean b = agentChatService.removeById(chat_id);
        if (!b){
          return R.error().message("删除失败");
        }
        return R.ok().message("删除成功");
    }

    /**
     *  历史查询
     * @param agentPageVo
     * @return
     */
    @PostMapping("/historyFind/{agent_chat_id}")
    @ApiOperation("历史查询")
    public R historyFind(@PathVariable int agent_chat_id,@RequestBody AgentPageVo agentPageVo) {
        if (ObjectUtils.isEmpty(agent_chat_id)){
            return R.error().message("智能体对话id不能为空");
        }
        IPage<AgentChat> tableIPage=agentChatTableService.listAll(agent_chat_id,agentPageVo);
        return R.ok().data(tableIPage);
    }

    /**
     * 查询历史分组
     * @param
     * @return
     */
    @GetMapping("/getHistoryGroup")
    @ApiOperation("查询历史分组")
    public R getHistoryGroup() {
        Long userId = UserHolder.get();
        String token = generateSecureToken();
        String s = HttpUtil.HttpsGetJson(BASE_URL+"chat/get_history_group", token, "user_id="+userId,"GET");
        JSONArray jsonObject = JSONArray.parseArray(s);
        return R.ok().data(jsonObject);
    }

    /**
     * 根据分组id查询历史对话（列表）
     * @param
     * @return
     */
    @GetMapping("/getHistoryByContentId/{content_id}/{agent_chat_id}")
    @ApiOperation("根据分组id查询历史对话（列表）")
    public R getHistoryByContentId(@PathVariable String content_id,@PathVariable int agent_chat_id) {
        Long userId = UserHolder.get();
        String token = generateSecureToken();
        String s = HttpUtil.HttpsGetJson(BASE_URL+"chat/get_history_by_content_id", token, "user_id="+userId+"&content_id="+content_id+"&agent_chat_id="+agent_chat_id,"GET");
        JSONArray jsonObject = JSONArray.parseArray(s);
        return R.ok().data(jsonObject);
    }

    /**
     * 根据分组id查询历史对话（列表）
     * @param
     * @return
     */
    @GetMapping("/getHistoryByAgentChatId/{agent_chat_id}")
    @ApiOperation("查询历史对话记录")
    public R getHistoryByAgentChatId(@PathVariable int agent_chat_id) {
        Long userId = UserHolder.get();
        String token = generateSecureToken();
        String s = HttpUtil.HttpsGetJson(BASE_URL+"chat/get_now_chat", token, "user_id="+userId+"&agent_chat_id="+agent_chat_id,"GET");
        JSONArray jsonObject = JSONArray.parseArray(s);
        return R.ok().data(jsonObject);
    }

    /**
     * 历史化对话（将当前对话转为历史，只用于查看，不能继续对话）
     * @param
     * @return
     */
    @PostMapping("/historize/{agent_chat_id}")
    @ApiOperation("清除上下文")
    public R historize(@PathVariable int agent_chat_id) {
        String token = generateSecureToken();
        Long userId = UserHolder.get();
        String s = HttpUtil.HttpsGetJson(BASE_URL+"chat/historize", token,"user_id="+userId+"&agent_chat_id="+agent_chat_id,"POST");
        return R.ok().data(s);
    }

    /**
     * 根据咨询师id查询到咨询师最近创建的一个智能体
     * @param couselor_id
     * @return
     */
    @GetMapping("/recentlyCreatedAgent")
    @ApiOperation("根据咨询师id查询到咨询师最近创建的一个智能体")
    public R recentlyCreatedAgent(@RequestParam("couselor_id") Long couselor_id) {
//        .orderByDesc(AgentTable::getCreateTime).last("limit 1")
        //查询到这条智能体数据
        AgentTable agent = agentTableService.getOneAgnet(couselor_id);
        Long userId = UserHolder.get();
        LambdaQueryWrapper<AgentChatTable> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AgentChatTable::getUserId,userId);
        wrapper.eq(AgentChatTable::getAgentId,agent.getAgentId());
        AgentChatTable agentChatTable = agentChatTableService.getOne(wrapper);
        //添加头像路径
        if (!ObjectUtils.isEmpty(agentChatTable)){
            if(!StringUtils.isEmpty(agentChatTable.getAgentProfile())){
                Long avatar = Long.valueOf(agentChatTable.getAgentProfile());
                File fileTrustUrl = fileService.getFileTrustUrl(avatar);
                if (!ObjectUtils.isEmpty(fileTrustUrl)){
                    agentChatTable.setAgentProfile(fileTrustUrl.getFileKey());
                }
            }
            return R.ok().data(agentChatTable);
        }

        //添加头像路径
        if(!StringUtils.isEmpty(agent.getAgentProfile())){
            Long avatar = Long.valueOf(agent.getAgentProfile());
            File fileTrustUrl = fileService.getFileTrustUrl(avatar);
            if (!ObjectUtils.isEmpty(fileTrustUrl)){
                agent.setAgentProfile(fileTrustUrl.getFileKey());
            }
        }

        return R.ok().data(agent);
    }





    /**
     * 生成智能体token
     * @return
     */
    private String generateSecureToken() {
        AgentTokenVo agentTokenVo = new AgentTokenVo();
        agentTokenVo.setSk("asdjfpwerijf12334asdflksdfjjisadfl");
        String time = String.valueOf(System.currentTimeMillis()/1000 + 10);
        agentTokenVo.setTime(time);
        //将textArray转换为json字符串
        String json = JSONObject.toJSONString(agentTokenVo);
        // 实现安全的token生成逻辑，这里保持原有逻辑作为示例
        String s1 = DigestUtils.md5DigestAsHex(json.getBytes());
        return "123456:"+s1+":"+time;
    }

    @GetMapping("/make")
    @ApiOperation("生成语音")
    public String makeFile(
            @RequestParam(required = false,defaultValue = "siyue",value = "voice")String Voice
            ,@RequestParam(required = false,defaultValue = "100")int PitchRate
            ,@RequestParam(required = false,defaultValue = "100")int Speech,
                           @RequestParam("chatId") int chatId){
        AgentChat byId = agentChatService.getById(chatId);
        if(ObjectUtils.isEmpty(byId)){
            return "该问题不存在";
        }
        //查询该问题对应的智能体对话
        AgentChatTable agentChatTable = agentChatTableService.getById(byId.getAgentChatId());
        if(!ObjectUtils.isEmpty(agentChatTable)){
            AgentTone agentTone = agentToneService.getById(agentChatTable.getUsageToneId());
            Voice=agentTone.getVoice();
        }
        System.out.println(byId.getAgentMsg()+" "+Voice+" "+PitchRate+" "+Speech);
        try {
            SpeechSynthesizerDemo demo = new SpeechSynthesizerDemo(appKey,ALIYUN_AK_ID,ALIYUN_AK_SECRET);
            demo.process(byId.getAgentMsg(),Voice,PitchRate,Speech);
            demo.shutdown();
            String Path = "http://8.142.120.232:9107"+SpeechSynthesizerDemo.resultPath.substring(51);
            //将路径保存到数据库
            agentChatService.saveOrUpdates(Path,chatId);
            //根据字数扣除积分
//            userService.updateUserScore(byId.getUserId(),-byId.getAgentMsg().length());
        } catch (Exception e) {
            return "error";
        }finally {
            System.out.println("返回结果  ->"+SpeechSynthesizerDemo.resultInfo+","+SpeechSynthesizerDemo.resultPath);
        }
        String resultPath = "http://8.142.120.232:9107"+SpeechSynthesizerDemo.resultPath.substring(51);
        return resultPath;
    }


    /**
     * 个性化人声获取文本
     * @param scenario
     * @return
     */
    @GetMapping("/getText")
    @ApiOperation("获取文本")
    public R getText(@RequestParam(required = false,defaultValue = "story",value = "scenario") String scenario){
        String text = PttsDemo.getText(scenario);
        Map mapObj = JSONObject.parseObject(text,Map.class);
        Object data = mapObj.get("Data");
        //随机生成0~19的随机数
        int i = new Random().nextInt(20);
        //获取到data中下标为i的
        Map map = (Map) ((List) data).get(i);
        return R.ok().data(map);
    }


    /**
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("uploadAudio")
    @ApiOperation("上传音频")
    public R uploadAudio(
            @RequestParam("file") MultipartFile file,
            @RequestParam("audioId")int audioId) throws IOException, InterruptedException {
        if (StringUtils.isEmpty(audioId)){
            return R.error().message("音频id不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        //获取文件扩展名
        String extensionName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        //生成随机UUID
        String guid = UUID.randomUUID().toString();
        //生成文件名
        String fileName = guid + "." + extensionName;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        //创建日期的字符串数组，格式为yyyy-MM-dd
        String[] split = formatter.format(new Date()).split("-");
        //创建文件路径的字符串
        String datePath = split[0] + java.io.File.separator + split[0] + split[1] + java.io.File.separator + split[0] + split[1] + split[2] + java.io.File.separator;
        //使用路径和文件名创建新的文件对象
        java.io.File destFile = new java.io.File(filePath + datePath + fileName);
        log.info("目标文件路径为：{}", destFile.getAbsolutePath());
        //检查文件的父目录是否存在，如果不创建它
        destFile.getParentFile().mkdirs();
        try {
            file.transferTo(destFile);
//            returnFile.setId(files.getId());
//            returnFile.setPath("/Data/" + datePath + fileName);
        } catch (Exception e){
            throw new ApiException(e);
        }
        String files="/Data/" + datePath + fileName;
        //voiceName
        Long userId = UserHolder.get();
        User user = userService.getById(userId);
        String gender="female";
        if (user.getSex()){
            //男
            gender="male";
        }
        String synthesize = PttsDemo.synthesize(user.getNickName(), "story", files, audioId, gender);
        Map mapObj = JSONObject.parseObject(synthesize,Map.class);
        Object data = mapObj.get("Data");
        //获取data中的ModelId
        Map map = (Map) ((List) data).get(0);
        Object modelId = map.get("ModelId");
        AgentTone agentTone = new AgentTone();
        //模型调用ID
        agentTone.setVoice((String) modelId);
        agentTone.setToneName(user.getNickName());
        agentTone.setToneTrade("阿里");
        agentTone.setToneOutback(1);
        agentToneService.save(agentTone);

        return R.ok().data(synthesize);

    }










}
